package com.example.wwk.graduationpractice.SmackUtils;

import android.util.Log;

import com.example.wwk.graduationpractice.NetDataUtils.LitePalUtils;
import com.example.wwk.graduationpractice.Bean.ComeMsgBean;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.offline.OfflineMessageManager;

import java.util.List;


/**
 * Created by wwk on 2017/4/8.
 * 获取离线消息
 */

public class GetOfflineMsgUtils {
    public static void getOffMessages(AbstractXMPPConnection connection) {
        OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);//获取离线信息
        try {
//            int count = offlineMessageManager.getMessageCount();
            List<Message> msgs = offlineMessageManager.getMessages();
            String receiver;
            String user;
            String receiverSub;
            String userSub;
            for (Message message : msgs) {
                receiver = message.getTo();
                user = message.getFrom();
                receiverSub=receiver.substring(0, receiver.indexOf("@"));
                userSub= user.substring(0, user.indexOf("@"));
                Log.d("123", "getOffMessages: to "+receiver+" from "+user);
                List<ComeMsgBean> comeMsgBeen = LitePalUtils.querryData(receiverSub,userSub );
                if (comeMsgBeen.size()==0) {      //当没有这两者的消息记录
                    LitePalUtils.addData(receiverSub, userSub, 1);
                }
                else {//当已经存在未读消息记录，这读取原有的数量并+1
                    for (ComeMsgBean comeMsgBeen1 : comeMsgBeen) {
                        int msgcount = comeMsgBeen1.getUnreadCount();
                        LitePalUtils.updateData(msgcount + 1, receiverSub, userSub);
                    }
                }
            }
            offlineMessageManager.deleteMessages();//通知服务器删除离线信息
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();

        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();

        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();

        }
    }
}
